//
//  GrabBillViewController.m
//  dangdang
//
//  Created by air on 16/2/2.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "GrabBillViewController.h"
#import "GXTextField.h"
#import "UIImageView+WebCache.h"

@interface GrabBillViewController ()

@property UIWebView * webView;
@property (nonatomic, strong) UIView * backView;
@property (nonatomic, copy) NSString * urlString;
@property (nonatomic, copy) NSString * phoneString;
@property (nonatomic, strong) GXTextField * textField;

@end

@implementation GrabBillViewController

- (instancetype)init {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"GrabBillViewController" bundle:nil];
    self = [sb instantiateViewControllerWithIdentifier:@"GrabBillViewController"];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self connection];
    
    [self updateUI];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    userObject.orderStatus = @"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)connection{
    if (![userObject.exp_uid isEqualToString:@"0"] && !(userObject.exp_uid == nil)) {
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.exp_uid;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        
        [self postRequestWithMethodName:@"user/get_info" andParams:params andSender:nil];
    }
}

- (void)updateUI{
    _waitLabel.layer.borderWidth = 1;
    _waitLabel.layer.borderColor = [[UIColor orangeColor] CGColor];
    _waitLabel.layer.cornerRadius = 4;
    _waitLabel.backgroundColor = [UIColor whiteColor];
    _waitLabel.layer.masksToBounds = YES;
    _bottomButton.layer.cornerRadius = 8;
    _headImageView.layer.cornerRadius = _headImageView.bounds.size.width / 2;
    _headImageView.layer.masksToBounds = YES;
    
    if (self.view.frame.size.width == 320) {
        for (NSLayoutConstraint * leftConstraint in _timeLabelConstraintArray) {
            leftConstraint.constant -= 10;
        }
        for (NSLayoutConstraint * widthConstraint in _imageViewConstraintArry) {
            widthConstraint.constant -= 35;
        }
        for (NSLayoutConstraint * lineLeftConstraint in _lineLeftConstraintArray) {
            lineLeftConstraint.constant -= 10;
        }
        for (UILabel * label in _grabLabelArray) {
            label.font = [UIFont systemFontOfSize:15.0];
        }
    }else if (self.view.frame.size.width == 414){
        for (NSLayoutConstraint * leftConstraint in _timeLabelConstraintArray) {
            leftConstraint.constant += 10;
        }
        for (NSLayoutConstraint * widthConstraint in _imageViewConstraintArry) {
            widthConstraint.constant += 20;
        }
        for (NSLayoutConstraint * lineLeftConstraint in _lineLeftConstraintArray) {
            lineLeftConstraint.constant += 10;
        }
    }
    
    [self judgeStatus];
    
    _pushButton.hidden = YES;
}

- (void)judgeStatus{
    if ([userObject.orderStatus isEqualToString:@"grab"] || userObject.array.count == 1 || (userObject.array.count == 2 && [userObject.pay_status isEqualToString:@"0"])) {
        for (UILabel * label in _timeLabelArray) {
            if (!(label.tag == 0)) {
                label.hidden = YES;
            }
        }
        for (UIImageView * imageView in _grabBackImageViewArray) {
            imageView.image = [UIImage imageNamed:@"hk_bg_up.png"];
        }
        for (UILabel * label in _grabLabelArray) {
            if (!(label.tag == 0)) {
                label.textColor = [UIColor lightGrayColor];
            }
        }
        _topView.hidden = YES;
        _bottomView.hidden = YES;
        _topViewConstraint.constant -= 70;
        for (NSLayoutConstraint * topConstraint in _lineTopConstraintArray) {
            topConstraint.constant -= 70;
        }
        for (NSLayoutConstraint * topConstraint in _dashedLinesTopConstraintArray) {
            topConstraint.constant -= 70;
        }
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[userObject.array.count - 1 - i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
//        [self identifying];
    }else if (userObject.array.count == 2 && [userObject.pay_status isEqualToString:@"1"]){
        for (UIImageView * imageView in _dashedLines) {
            imageView.hidden = YES;
        }
        for (UILabel * label in _timeLabelArray) {
            if (!(label.tag == 0) && !(label.tag == 1)) {
                label.hidden = YES;
            }
        }
        for (UIImageView * imageView in _grabBackImageViewArray) {
            if (!(imageView.tag == 0)) {
                imageView.image = [UIImage imageNamed:@"hk_bg_up.png"];
            }
        }
        for (UIImageView * imageView in _grabImageViewArray) {
            if (imageView.tag == 0) {
                imageView.image = [UIImage imageNamed:@"hk_orders_down.png"];
            }
        }
        for (UIView * view in _lineArray) {
            if (view.tag == 0) {
                view.backgroundColor = [UIColor orangeColor];
            }
        }
        for (UILabel * label in _grabLabelArray) {
            if (!(label.tag == 0) && !(label.tag == 1)) {
                label.textColor = [UIColor lightGrayColor];
            }
            if (label.tag == 1) {
                label.text = @"速送员接单";
            }
        }
        _waitLabel.hidden = YES;
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[userObject.array.count - 1 - i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
        [_bottomButton setTitle:@"购买并派送" forState:UIControlStateNormal];
    }else if (userObject.array.count == 3){
        //        self.navigationController.navigationBar.backgroundColor = [UIColor blackColor];
        for (UIImageView * imageView in _dashedLines) {
            imageView.hidden = YES;
        }
        for (UILabel * label in _timeLabelArray) {
            if (label.tag == 3) {
                label.hidden = YES;
            }
        }
        for (UIImageView * imageView in _grabBackImageViewArray) {
            if (imageView.tag == 2) {
                imageView.image = [UIImage imageNamed:@"hk_bg_up.png"];
            }
        }
        for (UIImageView * imageView in _grabImageViewArray) {
            if (imageView.tag != 2) {
                imageView.image = [UIImage imageNamed:@"hk_orders_down.png"];
            }
        }
        for (UIView * view in _lineArray) {
            if (view.tag != 2) {
                view.backgroundColor = [UIColor orangeColor];
            }
        }
        for (UILabel * label in _grabLabelArray) {
            if (label.tag == 3) {
                label.textColor = [UIColor lightGrayColor];
            }
            if (label.tag == 1) {
                label.text = @"速送员接单";
            }
        }
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[userObject.array.count - 1 - i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
        _waitLabel.hidden = YES;
        _bottomView.hidden = YES;
        [self identifying];
    }else if (userObject.array.count == 4){
        for (UIImageView * imageView in _dashedLines) {
            imageView.hidden = YES;
        }
        for (UIImageView * imageView in _grabImageViewArray) {
            imageView.image = [UIImage imageNamed:@"hk_orders_down.png"];
        }
        for (UIView * view in _lineArray) {
            view.backgroundColor = [UIColor orangeColor];
        }
        for (UILabel * label in _grabLabelArray) {
            if (label.tag == 1) {
                label.text = @"速送员接单";
            }
        }
        _waitLabel.hidden = YES;
        _bottomView.hidden = YES;
        for (int i = 0; i < userObject.array.count; i ++) {
            UILabel * label = _timeLabelArray[userObject.array.count - 1 - i];
            label.text = [NSString stringWithFormat:@"%@", [userObject.array[i] objectForKey:@"stime"]];
        }
    }
}

//- (IBAction)push:(UIButton *)sender {
//    _topView.hidden = NO;
//    _bottomView.hidden = NO;
//    _topViewConstraint.constant += 70;
//    for (NSLayoutConstraint * topConstraint in _lineTopConstraintArray) {
//        topConstraint.constant += 70;
//    }
//    for (NSLayoutConstraint * topConstraint in _dashedLinesTopConstraintArray) {
//        topConstraint.constant += 70;
//    }
//}

- (IBAction)phoneButton:(UIButton *)sender {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:_phoneString preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if (_webView == nil) {
            _webView = [[UIWebView alloc] init];
        }
        
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", _phoneString]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        [_webView loadRequest:request];
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    }];
    [alertVC addAction:action];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)identifying{
    _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    _backView.backgroundColor = [UIColor colorWithRed:10/255.0 green:10/255.0 blue:10/255.0 alpha:0.2];
    [self.view addSubview:_backView];
    
    UIView * evaluateView = [[UIView alloc] init];
    if ([UIScreen mainScreen].bounds.size.width == 375) {
        evaluateView.frame = CGRectMake(40, self.view.center.y - 200, self.view.frame.size.width - 80, 175);
    }else if ([UIScreen mainScreen].bounds.size.width == 414){
        evaluateView.frame = CGRectMake(60, self.view.center.y - 200, self.view.frame.size.width - 120, 175);
    }else{
        evaluateView.frame = CGRectMake(15, self.view.center.y - 200, self.view.frame.size.width - 30, 175);
    }
    evaluateView.backgroundColor = [UIColor whiteColor];
    evaluateView.layer.cornerRadius = 10;
    
    UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(evaluateView.bounds.size.width / 2 - 60, 14, 120, 22)];
    titleLabel.text = @"输入验证码";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:19.0];
    [evaluateView addSubview:titleLabel];
    
    _textField = [[GXTextField alloc] initWithFrame:CGRectMake(20, 56, evaluateView.bounds.size.width - 40, 42)];
    _textField.keyboardType = UIKeyboardTypeNumberPad;
    _textField.lengthOfText = 6;
    [evaluateView addSubview:_textField];
    
    UIView * lineB = [[UIView alloc] initWithFrame:CGRectMake(0, 124, evaluateView.bounds.size.width, 1)];
    lineB.backgroundColor = [UIColor lightGrayColor];
    [evaluateView addSubview:lineB];
    
    UIView * lineC = [[UIView alloc] initWithFrame:CGRectMake(evaluateView.bounds.size.width / 2, 125, 1, 50)];
    lineC.backgroundColor = [UIColor lightGrayColor];
    [evaluateView addSubview:lineC];
    
    UIButton * cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 125, evaluateView.bounds.size.width / 2, 50)];
    [cancelButton addTarget:self action:@selector(gxtextFieldButton:) forControlEvents:UIControlEventTouchUpInside];
    cancelButton.tag = 1;
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
    [evaluateView addSubview:cancelButton];
    
    UIButton * confirmButton = [[UIButton alloc] initWithFrame:CGRectMake(evaluateView.bounds.size.width / 2 + 1, 125, evaluateView.bounds.size.width / 2, 50)];
    [confirmButton addTarget:self action:@selector(gxtextFieldButton:) forControlEvents:UIControlEventTouchUpInside];
    confirmButton.tag = 2;
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor colorWithRed:60/255.0 green:120/255.0 blue:250/255.0 alpha:1.0] forState:UIControlStateNormal];
    confirmButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
    [evaluateView addSubview:confirmButton];
    
    [_backView addSubview:evaluateView];
}

- (void)gxtextFieldButton:(UIButton *)button{
    if (button.tag == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
//        if (_textField.text.length < 6) {
//            [self alertViewShowWithAlertString:@"验证码"];
//        }
        NSString * token = userObject.accessToken;
        NSString * orderIDString = userObject.ordID;
        NSString * valicodeString = _textField.text;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:valicodeString forKey:@"valicode"];
        [params setObject:orderIDString forKey:@"order_id"];
        
        [self postRequestWithMethodName:@"order/confirm_order" andParams:params andSender:nil];
    }
}

- (IBAction)bottonButton:(UIButton *)sender {
    if ([sender.titleLabel.text isEqualToString:@"购买并派送"]) {
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * orderIDString = userObject.ordID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:orderIDString forKey:@"order_id"];
        
        [self postRequestWithMethodName:@"order/sending_order" andParams:params andSender:nil];
    }else if ([sender.titleLabel.text isEqualToString:@"订单已完成"]){
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * orderIDString = userObject.ordID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:orderIDString forKey:@"order_id"];
        
        [self postRequestWithMethodName:@"order/confirm_order" andParams:params andSender:nil];
    }
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/confirm_order"]]){
            if ([code isEqualToString:@"0"]) {
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [self alertViewShowWithAlertString:@"验证码输入不正确请重新输入"];
                _textField.text = @"";
            }
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"user/get_info"]]){
            _urlString = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uhead"]];
//            NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_urlString]];
//            
//            _headImageView.image = [UIImage imageWithData:data];
            
            NSURL* imagePath = [NSURL URLWithString:_urlString];
            [_headImageView sd_setImageWithURL:imagePath];
            
            _nameLabel.text = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uname"]];
            _phoneString = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uphone"]];
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/sending_order"]]){
            if ([code isEqualToString:@"0"]) {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
